<template>
  <div class="app-container">
    <div class="title">我的题库</div>
    <!-- 搜索框展示 -->
    <el-row type="flex" justify="space-between">
      <el-col :span="16"> <el-input class="search-box" type="text" prefix-icon="el-icon-search" size="small"
          placeholder="输入题库名称搜索" v-model="queryParams.keyword" @keyup.enter.native="geSctktList">
        </el-input>
        <!-- 
        <el-button class="button-box" v-if="!isData" size="mini" @click="isData = !isData">+ 筛选</el-button>
        <el-button class="button-box" v-else size="mini" @click="isData = !isData">- 筛选</el-button> -->
      </el-col>

      <el-col :span="8">
        <el-button class="col-item" size="mini" type="primary">
          <router-link :to="{ name: 'addSctk' }" class="link">
            添加试题
          </router-link></el-button>

        <!-- <el-select class="col-item" v-model="sortType" placeholder="请选择" size="mini">
          <el-option v-for="item in sorts" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select> -->
      </el-col>
    </el-row>


    <!-- 详细搜索展示 -->

    <!-- <div class="search" v-show="isData">
      <div class="search-group">
        <span class="search-label">题库名称：</span>
        <el-input class="search-item" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入题库搜索"
          v-model="queryParams.name">
        </el-input>
      </div>
      <div class="search-group">
        <span class="search-label">手机号：</span>
        <el-input class="search-item" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入手机号搜索"
          v-model="queryParams.phone">
        </el-input>
      </div>
      <div class="search-group action-buttons">
        <el-button size="mini" type="success" @click="getCustomerList">查询</el-button>
        <el-button size="mini" @click="reset">重置</el-button>
      </div>
    </div> -->
    <!-- 内容表格 -->
    <div class="content">
      <el-table :data="userList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
        <el-table-column type="selection" width="55">
        </el-table-column>

        <el-table-column fixed label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button type="text" size="small">
              <!-- 使用 v-permission 指令 -->
              <router-link :to="{ name: 'addSctk', params: { id: scope.row.id } }" class="link">
                添加试题
              </router-link>

            </el-button>
            <el-button type="text" size="small">
              <!-- 使用 v-permission 指令 -->
              <router-link :to="{ name: 'questions', params: { id: scope.row.id } }" class="link">
                试题管理
              </router-link>
            </el-button>
            <!-- <el-button type="text" size="small">练习</el-button> -->
            <el-dropdown style="margin-left: 5px;" trigger="click">
              <el-button type="text" size="small">更多</el-button>
              <!-- <el-button type="text" size="small" @click="handleDelete(scope.row)">测试删除</el-button> -->
              <el-dropdown-menu slot="dropdown">
                <!-- <el-dropdown-item @click.native="setTop(scope.row)">置顶</el-dropdown-item> -->
                <el-dropdown-item v-if="scope.row.sort > 0" @click.native="cancelTop(scope.row)">
                  取消置顶
                </el-dropdown-item>
                <!-- 置顶 -->
                <el-dropdown-item v-else @click.native="setTop(scope.row)">
                  置顶
                </el-dropdown-item>
                <el-dropdown-item @click.native="editName(scope.row)">重命名</el-dropdown-item>
                <el-dropdown-item @click.native="editChapter(scope.row)">编辑章节</el-dropdown-item>
                <el-dropdown-item @click.native="editPassword(scope.row)">设置密码</el-dropdown-item>
                <el-dropdown-item @click.native="editClass(scope.row)">绑定班级</el-dropdown-item>
                <el-dropdown-item @click.native="delSctk(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column fixed prop="name" label="名称" align="center" width="300">
        </el-table-column>
        <el-table-column fixed prop="className" label="所属班级" align="center" width="300">
        </el-table-column>
        <el-table-column prop="num" label="题目数量" align="center" width="120">
        </el-table-column>
        <el-table-column prop="remake" label="简介" align="center" width="300">
        </el-table-column>
        <el-table-column prop="nick_name" label="创建人" align="center" width="120">
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间" align="center" width="200">
        </el-table-column>
        <el-table-column>
          <!-- 占空位 -->
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination @size-change="changePageSize" @current-change="changePageIndex"
        :current-page="queryParams.pageIndex" :page-sizes="[10, 20, 50]" :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="userTotal">
      </el-pagination>
    </div>
    <!-- 编辑章节弹层 -->
    <update-chapter v-if="updateChapterdialogId !== null" :show-dialog.sync="updateChapterShowDialog"
      :title="updateChapterdialogTitle" :fk_t_sctk_id="updateChapterdialogId" :chapters="chapters"
      @chapter-updated="getChapters"></update-chapter>
    <!-- 编辑题库弹层 -->
    <update-sctk-name v-if="updateNamedialogId !== null" :show-dialog.sync="updateNameShowDialog"
      :title="updateNamedialogTitle" :fk_t_sctk_id="updateNamedialogId" :row="currentRow"
      @submit="geSctktList"></update-sctk-name>
    <!-- 编辑密码弹层 -->
    <update-sctk-password v-if="updatePassworddialogId !== null" :show-dialog.sync="updatePasswordShowDialog"
      :title="updatePassworddialogTitle" :fk_t_sctk_id="updatePassworddialogId" :row="classRow"
      @submit="geSctktList"></update-sctk-password>
    <!-- 编辑所属班级弹层 -->
    <update-sctk-custom-class v-if="updateClassdialogId !== null" :show-dialog.sync="updateClassShowDialog"
      :title="updateClassdialogTitle" :fk_t_sctk_id="updateClassdialogId" :row="passwordRow"
      @submit="geSctktList"></update-sctk-custom-class>

  </div>
</template>
<script>


import { geSctktList, delSctk, setSctkTop } from '@/api/sctk';
import updateChapter from '@/components/updateChapter'
import updateSctkName from '@/components/updateSctkName'
import updateSctkPassword from '@/components/updateSctkPassword'
import updateSctkCustomClass from '@/components/updateSctkCustomerClass'
import { getSctktChapterList } from '@/api/sctkChapter'
import { transListToTreeDataOnChapter } from '@/utils'

export default {
  name: 'mySctk',
  components: { updateChapter, updateSctkName, updateSctkPassword, updateSctkCustomClass },
  created() {
    //访问后端客户接口
    this.geSctktList()
    // 初始化防抖函数

  },
  watch: {
    //监听变化
    sortType(newVal) {

      this.queryParams.sortType = newVal;
      this.geSctktList()
    },
    updateChapterShowDialog(newVal) {
      if (!newVal) {
        this.updateChapterdialogId = null; // 关闭时重置 id
      }
    }

  },
  data() {
    return {
      isData: false,
      sortType: '3',
      currentRow: null,
      passwordRow: null,
      classRow: null,
      updateChapterShowDialog: false,
      updateChapterdialogTitle: '编辑章节',
      updateChapterdialogId: null,
      chapters: [],
      updateNameShowDialog: false,
      updateNamedialogTitle: '编辑题库',
      updateNamedialogId: null,
      updatePassworddialogId: null,
      updatePasswordShowDialog: false,
      updatePassworddialogTitle: '设置密码',
      updateClassdialogId: null,
      updateClassShowDialog: false,
      updateClassdialogTitle: '绑定所属班级',
      userId: null,
      //批量选中
      selectedRows: [],
      // 用户总记录数
      userTotal: 0,
      userList: [],
      // 查询参数
      queryParams: {
        sortType: '3',
        pageIndex: 0,
        pageSize: 10,
        name: '',
        // 默认不查询 临时题库
        temp: '1',
        // phone: '',
        keyword: ''
      },
    }
  },
  methods: {
    goto() {
      this.$router.push({
        name: '', //  路由名称，
        params: { // params 参数
          id: 1,
          name: '张三'
        }, // 和name 配合


      })
      this.$router.push({
        path: '', // pasth 路由的地址
        query: { // query 参数
          id: 1,
          name: '张三'
        },// query 参数 和 path 配合使用
      })
    },
    async geSctktList() {
      const { data, total } = await geSctktList(this.queryParams)

      this.userList = data
      this.userTotal = total
    },
    // 监听表格选中变化
    handleSelectionChange(selection) {
      this.selectedRows = selection.map(row => row.id);

    },
    tableRowClassName({ row, rowIndex }) {
      // 判断是否是偶数行（索引从 0 开始）
      if (rowIndex % 2 === 1) {
        return 'even-row'; // 偶数行的类名
      }
      return ''; // 其他行不添加类名
    },
    changePageIndex(newPageIndex) {
      //切换页数
      this.queryParams.pageIndex = newPageIndex - 1
      this.geSctktList()
    },
    changePageSize(newPageSize) {
      //切换条数
      this.queryParams.pageSize = newPageSize
      //切换条数 页数默认置0
      this.queryParams.pageIndex = 0
      this.geSctktList()
    },
    handleDelete(row) {
      console.log('【handleDelete】被调用', row);
      this.delSctk(row);
    },
    async delSctk(row) {
      this.$confirm('删除后，可在【 回收站 】恢复', '确定要删除该题库吗？', {
        type: 'warning'
      })
        .then(async () => {
          await delSctk({ id: row.id });
          this.$message.success('删除成功');
          this.geSctktList();
        })
        .catch(action => {
          if (action === 'cancel') {
            console.log('用户点击了取消');
          } else {
            console.error('删除失败:', action);
          }
        });
    },
    async setTop(row) {
      //置顶
      await setSctkTop({ id: row.id })
      this.$message.success('置顶成功');
      this.geSctktList();
    },
    async cancelTop(row) {
      //置顶
      await setSctkTop({ id: row.id })
      this.$message.success('取消置顶成功');
      this.geSctktList();
    },

    editName(row) {
      this.currentRow = { name: row.name, remake: row.remake };
      this.updateNameShowDialog = true
      this.updateNamedialogTitle = '编辑名称'
      this.updateNamedialogId = row.id
    },
    editPassword(row) {
      this.passwordRow = { password: row.password, is_password: row.is_password };
      this.updatePasswordShowDialog = true
      this.updatePassworddialogTitle = '设置密码'
      this.updatePassworddialogId = row.id
    },
    editClass(row) {
      this.classRow = { fk_t_customer_class_id: row.fk_t_customer_class_id }
      this.updateClassShowDialog = true
      this.updateClassdialogTitle = '绑定班级'
      this.updateClassdialogId = row.id
    },
    // 编辑章节
    editChapter(row) {
      this.updateChapterShowDialog = true
      this.updateChapterdialogTitle = '编辑章节'
      this.updateChapterdialogId = row.id
      //这里查询章节
      this.getChapters(row.id)
    },
    reset() {
      this.queryParams = {
        sortType: '3',
        pageIndex: 0,
        pageSize: 10,
        name: '',
        // phone: '',
        keyword: ''
      }
    },
    async getChapters(id) {
      let result = await getSctktChapterList({ fk_t_sctk_id: this.updateChapterdialogId })
      // 递归处理
      this.chapters = transListToTreeDataOnChapter(result, 0)
      console.log('11111', this.chapters);

    }

  }

}
</script>
<style scoped>
.app-container {
  margin: 10px;
  background: #fff;
  border-radius: 5px;
  padding: 10px;

  .title {
    display: block;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    /* 文字居中对齐 */
    margin-bottom: 10px;
    /* 给标题下方留出间距 */
    border-bottom: 1px solid #e8eaec;
  }

  .search-box {
    width: 280px;
    /* 设置宽度 */
    height: 20px;
    /* 设置高度 */
    line-height: 20px;
    margin-bottom: 15px;
    margin-right: 10px;
    /* 确保输入框内容垂直居中 */
    font-size: 12px;
    /* 调整字体大小以适应高度 */
  }

  .button-box {
    /* 设置宽度 */
    height: 32px;
    /* 设置高度 */
    line-height: 20px;
    font-size: 12px;

  }

  .col-item {
    margin-left: 10px;
  }

  .search {
    margin-left: 10px;
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 20px;
  }

  /* 每个搜索组 */
  .search-group {
    display: flex;
    align-items: center;
    /* 垂直对齐 */
    width: calc(20% - 10px);
    margin-right: 30px;
    /* 每行放两个 */
  }

  .search-label {
    font-size: 12px;
    margin-top: 10px;
    color: #606266;
    /* 防止文字换行 */
  }

  .search-item {
    flex: 1;
    /* 输入框占据剩余空间 */
    height: 20px;
    line-height: 20px;
    font-size: 12px;

  }

  /* 按钮组样式 */
  .action-buttons {
    display: flex;
    margin-top: 10px;
    align-items: center;
    gap: 5px;
    /* 按钮之间的间距 */
    width: auto;
    /* 自适应宽度 */
  }

  .content {
    margin-top: 20px;

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }

  .pagination {
    margin-top: 20px;
  }




}
</style>
